import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

/// 通用头像组件
/// 支持网络图片、本地图片和文字头像，支持主题切换
class CommonAvatar extends StatelessWidget {
  /// 头像大小
  final double size;

  /// 网络图片URL
  final String? imageUrl;

  /// 本地图片路径
  final String? assetPath;

  /// 显示的文字（当没有图片时）
  final String? name;

  /// 背景颜色
  final Color? backgroundColor;

  /// 文字颜色
  final Color? textColor;

  /// 边框颜色
  final Color? borderColor;

  /// 边框宽度
  final double borderWidth;

  /// 点击事件
  final VoidCallback? onTap;

  /// 是否显示在线状态
  final bool? isOnline;

  const CommonAvatar({
    super.key,
    this.size = 40.0,
    this.imageUrl,
    this.assetPath,
    this.name,
    this.backgroundColor,
    this.textColor,
    this.borderColor,
    this.borderWidth = 0,
    this.onTap,
    this.isOnline,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Stack(
        children: [
          Container(
            width: size.w,
            height: size.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: borderWidth > 0
                  ? Border.all(
                      color: borderColor ?? Theme.of(context).dividerColor,
                      width: borderWidth,
                    )
                  : null,
            ),
            child: ClipOval(
              child: _buildAvatarContent(context),
            ),
          ),
          // 在线状态指示器
          if (isOnline != null)
            Positioned(
              right: 0,
              bottom: 0,
              child: Container(
                width: (size * 0.25).w,
                height: (size * 0.25).w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: isOnline! ? Colors.green : Colors.grey,
                  border: Border.all(
                    color: Theme.of(context).scaffoldBackgroundColor,
                    width: 2,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建头像内容
  Widget _buildAvatarContent(BuildContext context) {
    // 优先显示网络图片
    if (imageUrl != null && imageUrl!.isNotEmpty) {
      return Image.network(
        imageUrl!,
        width: size.w,
        height: size.w,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return _buildTextAvatar(context);
        },
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return Container(
            width: size.w,
            height: size.w,
            color: backgroundColor ??
                Theme.of(context).primaryColor.withOpacity(0.1),
            child: Center(
              child: SizedBox(
                width: (size * 0.4).w,
                height: (size * 0.4).w,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    Theme.of(context).primaryColor,
                  ),
                ),
              ),
            ),
          );
        },
      );
    }

    // 其次显示本地图片
    if (assetPath != null && assetPath!.isNotEmpty) {
      return Image.asset(
        assetPath!,
        width: size.w,
        height: size.w,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return _buildTextAvatar(context);
        },
      );
    }

    // 最后显示文字头像
    return _buildTextAvatar(context);
  }

  /// 构建文字头像
  Widget _buildTextAvatar(BuildContext context) {
    String displayText = '';
    if (name != null && name!.isNotEmpty) {
      // 取名字的第一个字符
      displayText = name!.substring(0, 1).toUpperCase();
    } else {
      displayText = '?';
    }

    return Container(
      width: size.w,
      height: size.w,
      color: backgroundColor ?? _getRandomColor(name),
      child: Center(
        child: Text(
          displayText,
          style: TextStyle(
            fontSize: (size * 0.4).sp,
            fontWeight: FontWeight.w500,
            color: textColor ?? Colors.white,
          ),
        ),
      ),
    );
  }

  /// 根据名字生成随机颜色
  Color _getRandomColor(String? text) {
    if (text == null || text.isEmpty) {
      return Colors.grey;
    }

    final colors = [
      Colors.blue,
      Colors.green,
      Colors.orange,
      Colors.purple,
      Colors.red,
      Colors.teal,
      Colors.indigo,
      Colors.pink,
    ];

    final index = text.hashCode % colors.length;
    return colors[index.abs()];
  }
}

/// 用户头像组件
/// 专门用于用户头像显示，包含更多用户相关功能
class UserAvatar extends StatelessWidget {
  /// 用户名
  final String? userName;

  /// 头像URL
  final String? avatarUrl;

  /// 头像大小
  final double size;

  /// 是否显示VIP标识
  final bool isVip;

  /// 是否显示认证标识
  final bool isVerified;

  /// 是否显示在线状态
  final bool? isOnline;

  /// 点击事件
  final VoidCallback? onTap;

  const UserAvatar({
    super.key,
    this.userName,
    this.avatarUrl,
    this.size = 50.0,
    this.isVip = false,
    this.isVerified = false,
    this.isOnline,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        CommonAvatar(
          size: size,
          imageUrl: avatarUrl,
          name: userName,
          onTap: onTap,
          isOnline: isOnline,
          borderWidth: isVip ? 2 : 0,
          borderColor: isVip ? Colors.amber : null,
        ),
        // VIP标识
        if (isVip)
          Positioned(
            top: 0,
            right: 0,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 1.h),
              decoration: BoxDecoration(
                color: Colors.amber,
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Text(
                'VIP',
                style: TextStyle(
                  fontSize: 8.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        // 认证标识
        if (isVerified)
          Positioned(
            bottom: 0,
            right: 0,
            child: Container(
              width: (size * 0.3).w,
              height: (size * 0.3).w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.blue,
                border: Border.all(
                  color: context.theme.scaffoldBackgroundColor,
                  width: 1,
                ),
              ),
              child: Icon(
                Icons.verified,
                size: (size * 0.2).w,
                color: Colors.white,
              ),
            ),
          ),
      ],
    );
  }
}

/// 头像组合组件
/// 用于显示多个头像的组合
class AvatarGroup extends StatelessWidget {
  /// 头像列表
  final List<String> avatars;

  /// 头像大小
  final double size;

  /// 最大显示数量
  final int maxCount;

  /// 重叠距离
  final double overlap;

  /// 点击事件
  final VoidCallback? onTap;

  const AvatarGroup({
    super.key,
    required this.avatars,
    this.size = 30.0,
    this.maxCount = 4,
    this.overlap = 10.0,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final displayAvatars = avatars.take(maxCount).toList();
    final remainingCount = avatars.length - maxCount;

    return GestureDetector(
      onTap: onTap,
      child: SizedBox(
        width: (size * displayAvatars.length -
                overlap * (displayAvatars.length - 1) +
                (remainingCount > 0 ? size : 0))
            .w,
        height: size.w,
        child: Stack(
          children: [
            // 显示头像
            ...displayAvatars.asMap().entries.map((entry) {
              final index = entry.key;
              final avatar = entry.value;
              return Positioned(
                left: (index * (size - overlap)).w,
                child: CommonAvatar(
                  size: size,
                  imageUrl: avatar,
                  borderWidth: 2,
                  borderColor: context.theme.scaffoldBackgroundColor,
                ),
              );
            }),
            // 显示剩余数量
            if (remainingCount > 0)
              Positioned(
                left: (displayAvatars.length * (size - overlap)).w,
                child: Container(
                  width: size.w,
                  height: size.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: context.theme.primaryColor.withOpacity(0.8),
                    border: Border.all(
                      color: context.theme.scaffoldBackgroundColor,
                      width: 2,
                    ),
                  ),
                  child: Center(
                    child: Text(
                      '+$remainingCount',
                      style: TextStyle(
                        fontSize: (size * 0.3).sp,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
